package by.grsu.transport.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import by.grsu.transport.converter.UserConverter;
import by.grsu.transport.model.User;
import by.grsu.transport.persistence.dao.DaoManager;
import by.grsu.transport.persistence.dao.UserDao;
import by.grsu.transport.persistence.dao.base.ConnectionBehavior;
import by.grsu.transport.persistence.dao.base.DaoCommand;
import by.grsu.transport.persistence.entity.UserEntity;
import by.grsu.transport.service.UserService;

public class UserServiceImpl implements UserService {

	private DaoManager daoManager;

	public UserServiceImpl(DaoManager daoManager) {
		this.daoManager = daoManager;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUsers(final User.Role role) throws SQLException {
		return (List<User>) daoManager.command(new DaoCommand() {

			@Override
			public Object execute(DaoManager daoManager) {
				UserDao userDao = daoManager.getDao(UserDao.class);
				int roleId = role.getOrdinal();
				List<UserEntity> listUserEntity = userDao.getUsers(roleId);
				List<User> listUser = new ArrayList<User>();
				for (UserEntity userEntity : listUserEntity) {
					listUser.add(UserConverter.getInstance().entityToModel(
							userEntity));
				}
				return listUser;
			}
		}, ConnectionBehavior.CLOSE);

	}

	@Override
	public User getUser(final String login) throws SQLException {

		return (User) daoManager.command(new DaoCommand() {

			@Override
			public Object execute(DaoManager daoManager) {
				UserDao userDao = daoManager.getDao(UserDao.class);
				return UserConverter.getInstance().entityToModel(
						userDao.getUser(login));
			}
		}, ConnectionBehavior.CLOSE);

	}

}
